<template>
  <main-card-admin title="算法仓库" :main-body-style-obj="{ paddingTop: '32px' }" :tabs="getTabs()">
    <template #tool-btn>
      <a-button v-auth="'algo-service-add'" type="primary" @click="handleEdit('add')"> 创建服务 </a-button>
    </template>
    <template #screen-space>
      <a-row class="page-top" :wrap="false">
        <a-col>
          <a-select
            ref="select"
            v-model:value="pageForm.typeId"
            :loading="dictionLoading"
            class="w-140"
            :options="(statusOptions as any[])"
            @change="getDataList({ offset: 1 })"
          />
        </a-col>
        <a-col flex="1" />
        <a-col>
          <a-input
            v-model:value="pageForm.algorithmName"
            v-trim
            allow-clear
            placeholder="请输入名称"
            style="width: 328px"
            @keyup.enter="getDataList()"
          >
            <template #prefix> <i class="iconfont icon-search-line" @click="getDataList()"></i> </template>
          </a-input>
        </a-col>
      </a-row>
    </template>
    <a-table
      :style="{ width: '100%' }"
      :pagination="false"
      :columns="tableColumns"
      :data-source="dataList"
      :custom-row="(r: any) => ({ onClick: () => previewRow(r) })"
      :loading="tableLoading"
      class="admin-table"
      @change="tableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'updateTime'">
          {{ dateFormat(record.updateTime) }}
        </template>
        <template v-else-if="column.dataIndex == 'algorithmName'">
          <a-tooltip placement="topLeft">
            <template #title>
              <span>{{ record.algorithmName }}</span>
            </template>
            <div v-if="record.algorithmName.length > 10" class="elliptical-1">{{ record.algorithmName }}</div>
            <span v-else>{{ record.algorithmName }}</span>
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex == 'typeNameString'">
          <div class="tag-list">
            <div v-for="item in record.typeNameString" :key="item" class="typeTag tag">
              <a-tooltip placement="topLeft">
                <template #title>
                  <span>{{ item }}</span>
                </template>
                {{ item }}
              </a-tooltip>
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex == 'labelNameString'">
          <div class="tag-list">
            <div v-for="item in record.labelNameString" :key="item" class="personalizedTag tag">
              <a-tooltip placement="topLeft">
                <template #title>
                  <span>{{ item }}</span>
                </template>
                {{ item }}
              </a-tooltip>
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex == 'status'">
          <a-tooltip v-if="record.status == 0 || record.status == 2 || record.status == 3" placement="bottom">
            <!-- <template #title>
              <span>{{ statusList[record.status]?.name?.substring(1) }}时间 {{ record?.statusTime || '' }}</span>
            </template> -->
            {{ statusList[record.status]?.name || '' }}
          </a-tooltip>
          <span v-else>{{ statusList[record.status]?.name || '' }}</span>
        </template>
        <template v-else-if="column.dataIndex == 'tools' && checkKey(['algo-service-edit', 'algo-version-add', 'algo-service-delete'])">
          <a-dropdown placement="bottom" :disabled="record.status == 0">
            <a-button type="text" class="icon-only-btn" :disabled="record.status == 0" @click.stop>
              <i class="iconfont icon-more-line"></i>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item v-if="checkKey('algo-service-edit')">
                  <li class="menu-icon-item" @click.stop="handleEdit('edit', record as RecordListItem)">
                    <i class="iconfont icon-edit-line"></i>
                    <span>编辑算法</span>
                  </li>
                </a-menu-item>
                <a-menu-item v-if="checkKey('algo-version-add')">
                  <li
                    class="menu-icon-item"
                    @click.stop="router.push(`/admin/algo-service-manage/version-add?algorithmId=${record.id}&parent=算法仓库`)"
                  >
                    <i class="iconfont icon-upload-2-line"></i>
                    <span>上传版本</span>
                  </li>
                </a-menu-item>
                <a-menu-item v-if="checkKey('algo-service-delete')">
                  <li class="menu-icon-item" @click.stop="handleOpenDeleteModal(record)">
                    <i class="iconfont icon-delete-bin-line"></i>
                    <span>删除算法</span>
                  </li>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-else>
          {{ column.dataIndex !== 'tools' ? replaceEmptyStr(record[column.dataIndex as string]) : '' }}
        </template>
      </template>
    </a-table>
    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList()" />
  </main-card-admin>
  <timer-modal
    v-model:open="timerModalVisible"
    title="确认删除"
    info="此算法服务所有版本将被删除，且不可恢复，请确认操作！"
    date-label="请选择删除时间"
    ok-text="确认并发送通知"
    @ok="handleDeleteVersion"
  />
</template>

<script lang="ts" setup>
  import { CheckboxOptionType, message } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import { checkKey } from '@/directives/auth'
  import useList from '@/hooks/use-list'
  import { algoDepotApi, tagManageApi } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'

  import TimerModal from '../components/timer-modal.vue'
  import { statusList } from '../options'
  import { DictionaryType, PageForm, RecordListItem } from '../types'

  const router = useRouter()
  import { getTabs } from '../utils'

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'algorithmName',
        width: 180
      },
      {
        title: '服务类型',
        dataIndex: 'typeNameString'
      },
      {
        title: '服务标签',
        dataIndex: 'labelNameString'
      },
      {
        title: '版本数量',
        dataIndex: 'versionCount',
        width: 120
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 100
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        isSort: true,
        width: 200
      },
      {
        title: '',
        width: 100,
        dataIndex: 'tools',
        align: 'right'
      }
    ])
  )

  /******************** 获取字典信息 ************************/
  const statusOptions = ref<CheckboxOptionType[]>([])
  const { loading: dictionLoading, runAsync: getDictionaryRun } = useRequest<ResponseData<DictionaryType[]>>(tagManageApi.list, {
    onSuccess: ({ data }) => {
      statusOptions.value = [
        {
          label: '全部类型',
          value: ''
        },
        ...data.map((item: DictionaryType) => ({ label: item.v, value: item.id }))
      ] as CheckboxOptionType[]
    }
  })

  const previewRow = (row: any) => {
    router.push(`/admin/algo-service-manage/detail/${row.id}`)
  }
  const tableChange = (pagination: any, filters: any, sorter: any) => {
    pageForm.value.columns = sorter.field
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getDataList({ offset: 1 })
  }

  // 删除算法
  const timerModalVisible = ref<boolean>(false)
  let _row_: any = null
  const handleDeleteVersion = (time: any) => runDelete(_row_.id, time)
  const handleOpenDeleteModal = (row: any) => {
    _row_ = row
    timerModalVisible.value = true
  }
  const { loading: tableLoading, runAsync: runDelete } = useRequest(algoDepotApi.delete, {
    onSuccess: () => {
      timerModalVisible.value = false
      message.success('操作成功')
      getDataList()
    }
  })

  /* 编辑页 */
  const handleEdit = (type: 'add' | 'edit', item?: RecordListItem) => {
    console.log(item)
    if (type === 'add') {
      router.push(`/admin/algo-service-manage/add`)
      return
    }
    router.push(`/admin/algo-service-manage/edit/${item?.id}`)
  }

  const { pageForm, dataList, getDataList } = useList<PageForm, any>(algoDepotApi.list, {
    algorithmName: '',
    typeId: '',
    order: 'desc',
    columns: 'updateTime'
  })

  getDictionaryRun({
    type: 'type_tag'
  })
  getDataList()
</script>

<style lang="less" scoped>
  .tag-list {
    display: flex;
    align-items: center;
  }

  .tag {
    display: inline-block;
    align-items: center;
    overflow: hidden;
    padding: 2px 6px;
    margin-right: 4px;
    text-overflow: ellipsis;
    white-space: nowrap;
    border: 1px solid rgba(0, 0, 0, 0.05);
    border-radius: 6px;

    &.typeTag {
      color: #4686ed;
      background: rgba(65, 84, 209, 0.08);
    }

    &.personalizedTag {
      color: #d61860;
      background: rgba(214, 24, 96, 0.08);
    }
  }
</style>
